package com.back.network.netty;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.back.network.netty.container.Container;
import com.back.network.netty.handlers.ChildProxyChannel;
import com.back.network.netty.handlers.ChildUserChannel;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

@Component
public class ProxyServerContainer implements Container {

	private static Logger logger = LoggerFactory.getLogger(ProxyServerContainer.class);

	private NioEventLoopGroup serverWorkerGroup;

	private NioEventLoopGroup serverBossGroup;

	@Resource
	private ChildProxyChannel childProxyChannel;

	@Resource
	private ChildUserChannel childUserChannel;

	public ProxyServerContainer() {

		serverBossGroup = new NioEventLoopGroup();
		serverWorkerGroup = new NioEventLoopGroup();
	}

	@Override
	public void start() {
		ServerBootstrap bootstrap = new ServerBootstrap();
		bootstrap.group(serverBossGroup, serverWorkerGroup).channel(NioServerSocketChannel.class)
				.childHandler(childProxyChannel);

		try {
			bootstrap.bind(4399).get();
			logger.info("代理服务启动成功端口 = " + 4399);
		} catch (Exception e) {
			logger.info("代理服务启动失败 = " + e.getMessage());
			e.printStackTrace();
		}
		
		startHttpServiec();

	}

	@Override
	public void startHttpServiec() {
		ServerBootstrap bootstrap = new ServerBootstrap();
		bootstrap.group(serverBossGroup, serverWorkerGroup).channel(NioServerSocketChannel.class)
				.childHandler(childUserChannel);

		try {
			//1573开放给http协议
			bootstrap.bind(1573).get();
			//1574开放给https协议
			bootstrap.bind(1574).get();
			logger.info("HTTP代理服务启动成功");
		} catch (Exception e) {
			logger.info("HTTP代理服务启动失败 = " + e.getMessage());
			e.printStackTrace();
		}
	}

	@Override
	public void startUserService(int port) {
		ServerBootstrap bootstrap = new ServerBootstrap();
		bootstrap.group(serverBossGroup, serverWorkerGroup).channel(NioServerSocketChannel.class)
				.childHandler(childUserChannel);

		try {
			bootstrap.bind(port).get();
			logger.info("代理服务启动成功端口 = " + port);
		} catch (Exception e) {
			logger.info("用户服务启动失败 = " + e.getMessage());
			e.printStackTrace();
		}
	}

	@Override
	public void stop() {
		serverBossGroup.shutdownGracefully();
		serverWorkerGroup.shutdownGracefully();
	}

}
